<template>
  <div class="app-container">
    <!-- 基本信息 -->
    <el-card class="box-card" style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <span>基本信息</span>
        </div>
      </template>
      
      <el-form ref="activityRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="form.activityName" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="报名截止时间" prop="applyEndTime">
              <el-date-picker
                v-model="form.applyEndTime"
                type="datetime"
                placeholder="请选择报名截止时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="活动开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                placeholder="请选择活动开始时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="抢购时间段" prop="timeSegments">
          <div class="time-segments-container">
            <!-- 时间段标签显示 -->
            <div class="time-tags-area">
              <el-tag
                v-for="(segment, index) in timeSegments"
                :key="index"
                closable
                @close="removeTimeSegment(index)"
                class="time-tag"
              >
                {{ segment.timeSegment || segment }}
              </el-tag>
            </div>
            
            <!-- 添加时间段输入区域 -->
            <div class="add-time-segment">
              <el-input
                v-model="newTimeSegment"
                placeholder="2"
                style="width: 100px; margin-right: 10px;"
                @keyup.enter="addTimeSegment"
                @blur="formatTimeInput"
                @input="handleTimeInput"
              />
              <el-button 
                type="primary" 
                size="small" 
                @click="addTimeSegment"
              >
                添加时间段
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="申请规则" prop="applyRule">
              <el-input v-model="form.applyRule" placeholder="请输入申请规则" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    
    <!-- 操作按钮 -->
    <div class="footer-buttons">
      <el-button @click="goBack">返回</el-button>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getActivitiess, 
  updateActivitiess, 
  addTimeSegment as addTimeSegmentAPI, 
  deleteTimeSegment,
  getTimeSegments
} from "@/api/promotion/activitiess"

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

// 表单数据
const form = ref({
  id: null,
  activityName: '',
  applyEndTime: '',
  startTime: '',
  applyRule: ''
})

// 时间段数据 - 从数据库获取
const timeSegments = ref([])

// 新增的时间段（需要保存到数据库的）
const newTimeSegments = ref([])

// 新时间段输入
const newTimeSegment = ref('')

// 表单验证规则
const rules = reactive({
  activityName: [
    { required: true, message: '活动名称不能为空', trigger: 'blur' }
  ],
  applyEndTime: [
    { required: true, message: '报名截止时间不能为空', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '活动开始时间不能为空', trigger: 'change' }
  ],
  applyRule: [
    { required: true, message: '申请规则不能为空', trigger: 'blur' }
  ]
})

// 获取活动详情
const getActivityDetail = async () => {
  const activityId = route.params.id || route.query.id
  if (activityId) {
    try {
      const response = await getActivitiess(activityId)
      form.value = response.data
      
      // 获取时间段数据
      const timeSegmentResponse = await getTimeSegments(activityId)
      const segments = timeSegmentResponse.data || []
      
      // 保存完整的时间段对象，包含ID用于删除
      timeSegments.value = segments.map(segment => {
        // 确保返回包含id和timeSegment的对象
        if (typeof segment === 'object' && segment.timeSegment) {
          return {
            id: segment.id,
            timeSegment: segment.timeSegment
          }
        }
        return {
          id: segment.id || null,
          timeSegment: segment.timeSegment || segment
        }
      })
    } catch (error) {
      ElMessage.error('获取活动详情失败')
    }
  }
}

// 格式化时间输入
const formatTimeInput = () => {
  if (newTimeSegment.value && newTimeSegment.value.trim()) {
    const input = newTimeSegment.value.trim()
    
    // 如果是纯数字，自动添加 :00:00
    if (/^\d+$/.test(input)) {
      newTimeSegment.value = `${input}:00:00`
    }
    // 如果是 HH:MM 格式，自动添加 :00
    else if (/^\d{1,2}:\d{2}$/.test(input)) {
      newTimeSegment.value = `${input}:00`
    }
  }
}

// 处理输入过程中的格式化
const handleTimeInput = (value) => {
  // 可以在这里添加实时格式化逻辑，如果需要的话
}

// 添加时间段
const addTimeSegment = () => {
  if (newTimeSegment.value && newTimeSegment.value.trim()) {
    const formattedTime = newTimeSegment.value.trim()
    
    // 检查是否已存在相同的时间段
    const existingTimes = timeSegments.value.map(segment => segment.timeSegment || segment)
    if (!existingTimes.includes(formattedTime)) {
      const newSegment = { id: null, timeSegment: formattedTime }
      timeSegments.value.push(newSegment)
      newTimeSegments.value.push(formattedTime) // 记录新增的时间段
      newTimeSegment.value = ''
    } else {
      ElMessage.warning('该时间段已存在')
    }
  }
}

// 删除时间段
const removeTimeSegment = async (index) => {
  const segment = timeSegments.value[index]
  
  try {
    // 如果是数据库中的时间段（有ID），则调用删除API
    if (segment.id) {
      await deleteTimeSegment(segment.id)
    }
    
    // 从本地数组中移除
    timeSegments.value.splice(index, 1)
    
    // 如果是新增的时间段，也要从新增列表中移除
    const timeSegmentValue = segment.timeSegment || segment
    const newIndex = newTimeSegments.value.indexOf(timeSegmentValue)
    if (newIndex > -1) {
      newTimeSegments.value.splice(newIndex, 1)
    }
    
    ElMessage.success('时间段删除成功')
  } catch (error) {
    ElMessage.error('时间段删除失败：' + error.message)
  }
}

// 保存表单
const submitForm = async () => {
  try {
    // 验证基本信息表单
    await proxy.$refs.activityRef.validate()
    
    // 保存活动基本信息
    await updateActivitiess(form.value)
    
    // 只保存新增的时间段信息
    for (const segment of newTimeSegments.value) {
      if (segment) {
        await addTimeSegmentAPI({
          seckillActivityId: form.value.id,
          timeSegment: segment,
          createTime: new Date(),
          updateTime: new Date()
        })
      }
    }
    
    // 保存成功后清空新增时间段记录
    newTimeSegments.value = []
    
    ElMessage.success('保存成功')
    goBack()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 返回列表页
const goBack = () => {
  router.push('/promotion/activitiess')
}

// 组件挂载时获取数据
onMounted(() => {
  getActivityDetail()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.box-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    font-size: 16px;
  }
}

.time-segments-container {
  .time-tags-area {
    margin-bottom: 15px;
    
    .time-tag {
      margin-right: 8px;
      margin-bottom: 8px;
      padding: 6px 12px;
      font-size: 14px;
      border-radius: 4px;
      background-color: #f0f9ff;
      border-color: #d1e7dd;
      color: #0369a1;
      
      &:hover {
        background-color: #e0f2fe;
      }
    }
  }
  
  .add-time-segment {
    display: flex;
    align-items: center;
    
    .el-input {
      margin-right: 10px;
    }
  }
}

.footer-buttons {
  text-align: center;
  margin-top: 30px;
  
  .el-button {
    margin: 0 10px;
    padding: 12px 30px;
  }
}
</style>